package com.example.base.http.interceptor;

import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.example.base.http.exception.ApiException;
import com.example.base.utils.MMKVUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class BaseInterceptor implements Interceptor {
    private Map<String, String> headers;

    public BaseInterceptor(Map<String, String> headers) {
        this.headers = headers;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Request.Builder requestBuilder = request.newBuilder();
        if (headers != null && headers.size() > 0) {
            Set<String> keys = headers.keySet();
            for (String headerKey : keys) {
                requestBuilder.addHeader(headerKey, headers.get(headerKey));
            }
        } else {
            // 添加公共Header
            if (SPUtils.getInstance().contains("token")) {
                requestBuilder.addHeader("token", SPUtils.getInstance().getString("token",""));
            }
        }

        if ("GET".equals(request.method())){
            HttpUrl url = request.url();
            HttpUrl newUrl = url.newBuilder()
                    .addEncodedQueryParameter("langCode", "zh_CN")
                    .build();
            requestBuilder.url(newUrl);
        }

        if ("POST".equals(request.method())){
            // 构造新的请求表单
            FormBody.Builder builder = new FormBody.Builder();

            FormBody body = (FormBody) request.body();
            //将以前的参数添加
            for (int i = 0; i < body.size(); i++) {
                builder.add(body.encodedName(i), body.encodedValue(i));
            }
            //追加新的参数
            builder.add("langCode", "zh_TW");
            requestBuilder.post(builder.build());
        }

        // 请求信息
        return chain.proceed(requestBuilder.build());
    }
}